<?php

namespace app\api\controller;

use app\common\controller\Api;
use app\common\library\Ems;
use app\common\library\Sms;
use app\common\library\Wechat;
use app\common\model\MoneyLog;
use app\common\model\order\Order;
use app\common\model\ScoreLog;
use app\common\model\User as ModelUser;
use app\common\model\user\Address;
use app\common\model\user\Enter;
use app\common\model\user\Level;
use app\common\model\user\LevelLog;
use app\common\model\user\Withdrawal;
use fast\Random;
use think\Config;
use think\Db;
use think\Validate;

/**
 * 会员接口
 */
class User extends Api
{
    protected $noNeedLogin = ['login', 'mobilelogin', 'wxLogin', 'resetpwd', 'changeemail', 'changemobile'];
    protected $noNeedRight = '*';

    public function _initialize()
    {
        parent::_initialize();

        if (!Config::get('fastadmin.usercenter')) {
            $this->error(__('User center already closed'));
        }
    }
    /**
     * 会员登录
     *
     * @ApiMethod (POST)
     * @param string $account  账号
     * @param string $password 密码
     */
    public function login()
    {
        $account = $this->request->post('account');
        $password = $this->request->post('password');
        if (!$account || !$password) {
            $this->error(__('Invalid parameters'));
        }
        $ret = $this->auth->login($account, $password);
        if ($ret) {
            $data = ['userinfo' => $this->auth->getUserinfo()];
            $this->success(__('Logged in successful'), $data);
        } else {
            $this->error($this->auth->getError());
        }
    }
    /**
     * 微信小程序登录
     *
     * @params string $code 微信授权code
     * @params string $phoneCode 电话授权code
     * @params string $nickname 昵称
     * @params string $avatar 头像
     * @params string $qr_code 邀请码
     * @return array
     */
    public function wxLogin()
    {
        $params = $this->request->param();
        extract($params);
        // 入参
        if (empty($code)) {
            $this->error('缺少必要参数!');
        }
        $result = [];
        try {
            $wechat = new Wechat('wxMiniProgram');
            $decryptSession = $wechat->code($code);
            if (!isset($decryptSession['session_key'])) {
                exception($decryptSession['errmsg']);
            }
            if (!$decryptSession || !isset($decryptSession['openid'])) {
                exception('未获取到登录状态,请重试!');
            }
            if (empty($decryptSession['openid'])) {
                exception('code错误,请重试!');
            }
            // 分参
            // $decrypt = $wechat->getAccessToken();
            // $token = $decrypt['access_token'];
            // $url = "https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=$token";
            // $client = new \GuzzleHttp\Client();
            // $response = $client->post($url, [
            //     'json' => [        //参数组
            //         'code' => $phoneCode
            //     ]
            // ]);
            // $res = $response->getBody();
            // $res = json_decode($res, 1);
            // if ($res['errcode'] == 0) {
            //     $phone = $res['phone_info'];
            // } else {
            //     exception('失败:' . $res['errmsg']);
            // }
            $user = \app\common\model\User::get([
                'openid'   => $decryptSession['openid']
            ]);
            if (!empty($user)) {
                if ($user->status != 'normal') {
                    exception(__('Account is locked'));
                }
                $user->save();
                // 直接登陆
                $result = $this->auth->direct($user->id);
            } else {
                if (isset($qr_code) && !empty($qr_code)) {
                    $decryptSession['qr_code'] = $qr_code;
                }
                // $decryptSession['phoneNumber'] = $phone['phoneNumber'] ?? '';
                $decryptSession['nickname'] = $nickname ?? '';
                // 写入个人数据
                $result = $this->auth->oauthRegister($decryptSession);
            }
        } catch (\Exception $e) {
            $this->error($e->getMessage());
        }
        if ($result) {
            $this->success('授权登录成功', $this->auth->getUserInfo());
        } else {
            $this->error('授权登录失败了!' . $this->auth->getError());
        }
    }
    /**
     * 会员中心
     */
    public function index()
    {
        $uid = $this->auth->id;
        $userInfo = ModelUser::get($this->auth->id);
        $userInfo->economize = Order::where('status', '>', 0)->where('user_id', $userInfo->id)->sum('vip_deduction');
        $userInfo->total_earnings = MoneyLog::where('type', '1')->where('user_id', $uid)->whereIn('source_type', [100, 101, 102,103])->sum('money');
        $userInfo->withdraw = Withdrawal::where('state', '2')->where('user_id', $uid)->sum('money');
        $userInfo->vip_price = Level::value('price');
        $this->success('', $userInfo);
    }


    /**
     * 退出登录
     * @ApiMethod (POST)
     */
    public function logout()
    {
        if (!$this->request->isPost()) {
            $this->error(__('Invalid parameters'));
        }
        $this->auth->logout();
        $this->success(__('Logout successful'));
    }

    /**
     * 修改会员个人信息
     *
     * @ApiMethod (POST)
     * @param string $avatar   头像地址
     * @param string $username 用户名
     * @param string $nickname 昵称
     * @param string $bio      个人简介
     */
    public function profile()
    {
        $user = $this->auth->getUser();
        $nickname = $this->request->post('nickname');
        $avatar = $this->request->post('avatar', '', 'trim,strip_tags,htmlspecialchars');
        if ($nickname) {
            $user->nickname = $nickname;
        }
        $user->avatar = $avatar;
        $user->save();
        $this->success();
    }

    /**
     * 修改手机号
     * @ApiInternal
     * @ApiMethod (POST)
     * @param string $mobile  手机号
     * @param string $captcha 验证码
     */
    public function changemobile()
    {
        $user = $this->auth->getUser();
        $mobile = $this->request->post('mobile');
        $captcha = $this->request->post('captcha');
        if (!$mobile || !$captcha) {
            $this->error(__('Invalid parameters'));
        }
        if (!Validate::regex($mobile, "^1\d{10}$")) {
            $this->error(__('Mobile is incorrect'));
        }
        if (\app\common\model\User::where('mobile', $mobile)->where('id', '<>', $user->id)->find()) {
            $this->error(__('Mobile already exists'));
        }
        $result = Sms::check($mobile, $captcha, 'changemobile');
        if (!$result) {
            $this->error(__('Captcha is incorrect'));
        }
        $verification = $user->verification;
        $verification->mobile = 1;
        $user->verification = $verification;
        $user->mobile = $mobile;
        $user->save();

        Sms::flush($mobile, 'changemobile');
        $this->success();
    }



    /**
     * 获取用户收货地址
     *
     * @ApiMethod (GET)
     */
    public function getUserAddress()
    {
        $uid = $this->auth->id;
        $data = Address::getUserAddress($uid);
        $this->success('获取成功', $data);
    }
    /**
     * 获取用户默认地址
     *
     * @ApiMethod (GET)
     */
    public function getDefaultAddress()
    {
        $uid = $this->auth->id;
        $list = Address::getDefaultAddress($uid);
        $this->success('获取成功', $list);
    }
    /**
     * 设置用户默认地址
     *
     * @ApiMethod (POST)
     * @param string $id  地址id
     * 
     */
    public function setDefaultAddress()
    {
        $post = $this->request->post();
        extract($post);
        if (!isset($id) || empty($id)) {
            $this->error('参数错误');
        }
        $uid = $this->auth->id;
        Address::setDefaultAddress($id, $uid);
        $this->success('设置成功');
    }
    /**
     * 添加收货地址
     *
     * @ApiMethod (POST)
     * @param string $contact  收货人
     * @param string $telephone  手机号
     * @param string $province  省
     * @param string $city  市
     * @param string $area  区
     * @param string $address  地址
     * @param string $longitude  经度
     * @param string $latitude  纬度
     * 
     */
    public function addAddress()
    {
        $post = $this->request->post();
        $validate = validate('user.Address'); //使用助手函数
        $result = $validate->check($post);
        if (!$result) {
            $this->error($validate->getError());
        }
        $post['user_id'] = $this->auth->id;
        $res = Address::AddAddress($post);
        if ($res !== false) {
            $this->success('提交成功', $res);
        }
        $this->error('提交失败');
    }
    /**
     * 删除用户收货地址
     *
     * @ApiMethod (POST)
     * @param string $id  地址id
     * 
     */
    public function delAddress()
    {
        $post = $this->request->post();
        extract($post);
        if (!isset($id) || empty($id)) {
            $this->error('参数错误');
        }
        $data = Address::get($id);
        $data->delete();
        $this->success('删除成功', $data);
    }


    /**
     * 开通会员
     *
     * @ApiMethod (POST)
     */
    public function openVip()
    {
        $level = Level::find();
        if (!$level) {
            $this->error('开通失败，会员不存在');
        }
        $log = new LevelLog([
            'user_id' => $this->auth->id,
            'sn' => sn('level_log', 'sn', 'LV'),
            'pay_fee' => $level->price,
            'point' => $level->score,
            'level_id' => $level->id,
        ]);
        $res = $log->save();
        if ($res) {
            $this->success('', $log->id);
        }
        $this->error('开通失败');
    }

    /**
     * @Author LK
     * @ApiTitle (用户提现)
     * @ApiMethod (POST)
     * @ApiParams (name="money", type="string", required=true, sample="", description="提现金额")
     * @ApiReturnParams (name="code", type="integer", required=true, description="")
     * @ApiReturn ({'code':1,'msg':'返回成功'})
     */
    public function withdrawal()
    {
        $post = $this->request->post();
        $uid = $this->auth->id;
        $user = ModelUser::get($uid);
        extract($post);
        Db::startTrans();
        try {
            $post['sn'] = sn('user_withdrawal', 'sn', 'TX');
            $post['user_id'] = $uid;
            $min_withdrawn = config('site.min_withdrawn');
            if ($money < $min_withdrawn) {
                exception('最低提现' . $min_withdrawn);
            }
            if ($money > $user->money) {
                exception('余额不足');
            }
            $tx = new Withdrawal($post);
            $tx->allowField(true)->save();
            MoneyLog::income($uid, $money, 2, 500, $post['sn']);
            Db::commit();
        } catch (\Exception $th) {
            Db::rollback();
            $this->error($th->getMessage());
        }
        $this->success('申请成功');
    }
    /**
     * @Author LK
     * @ApiTitle (提现明细)
     * @ApiMethod (GET)
     * @ApiReturnParams (name="code", type="integer", required=true, description="")
     * @ApiReturn ({'code':1,'msg':'返回成功'})
     */
    public function withdrawalInfo()
    {
        $get = request()->get();
        extract($get);
        if (!isset($get) || empty($get)) {
            $this->error('参数错误');
        }
        $tx = new Withdrawal();
        $list = $tx->where('user_id', $this->auth->id)->order('id desc')->paginate();
        $this->success('', $list);
    }
    /**
     * @Author LK
     * @ApiTitle (申请入驻)
     * @ApiMethod (POST)
     * @ApiParams (name="type", type="integer", required=true, sample="", description="(1=员工入驻；2=业务员入驻；3=合作商入驻)")
     * @ApiParams (name="name", type="string", required=true, sample="", description="姓名")
     * @ApiParams (name="phone", type="string", required=true, sample="", description="手机号")
     * @ApiParams (name="category_ids", type="string", required=true, sample="", description="服务类型")
     * @ApiParams (name="content", type="string", required=true, sample="", description="申请理由")
     * @ApiParams (name="images", type="string", required=true, sample="", description="图片")
     * @ApiParams (name="profession", type="string", required=true, sample="", description="经营行业")
     * @ApiReturnParams (name="code", type="integer", required=true, description="")
     * @ApiReturn ({'code':1,'msg':'返回成功'})
     */
    public function addEnter()
    {
        $post = request()->post();
        extract($post);
        $validate = validate('user.Enter');
        switch ($type) {
            case 1:
                $result = $validate->scene('employee')->check($post);
                break;
            case 2:
                $result = $validate->scene('salesman')->check($post);
                break;
            case 3:
                $result = $validate->scene('partner')->check($post);
                break;
        }
        if (!$result) {
            $this->error($validate->getError());
        }
        $post['user_id'] = $this->auth->id;
        $enter = new Enter($post);
        $res = $enter->allowField(true)->save();
        if ($res) {
            $this->success('申请成功');
        }
        $this->error('失败');
    }
    /**
     * @Author LK
     * @ApiTitle (收益明细)
     * @ApiMethod (POST)
     * @ApiReturnParams (name="code", type="integer", required=true, description="")
     * @ApiReturn ({'code':1,'msg':'返回成功'})
     */
    public function money_log()
    {
        $list = MoneyLog::where('user_id', $this->auth->id)->order('id desc')->paginate(10);
        $this->success('', $list);
    }
    /**
     * @Author LK
     * @ApiTitle (积分明细)
     * @ApiMethod (POST)
     * @ApiReturnParams (name="code", type="integer", required=true, description="")
     * @ApiReturn ({'code':1,'msg':'返回成功'})
     */
    public function Score_log()
    {
        $list = ScoreLog::where('user_id', $this->auth->id)->order('id desc')->paginate(10);
        $this->success('', $list);
    }
}
